<?php

namespace app\mobileapp\controller;

use app\mobileapp\controller\Base;
use service\WechatService;
use think\Db;
use think\facade\Cache;
use service\SmsService;

class Account extends Base
{

    const SMS_LOGIN = 1;

    /**
     * User: Simony
     * Function:登录
     */
    public function login()
    {
        $mobile = input('post.mobile', '');
        $code = input('post.code', '');
        $lng = input('post.longitude', 113.278121);
        $lat = input('post.latitude', 23.135911);

        if (empty($mobile)) $this->api_ajaxReturn(ERROR, '手机号码不能为空');

        $verify = SmsService::verify($mobile, $code);
        if (!$verify['status']) $this->api_ajaxReturn(ERROR, $verify['msg']);

        $memberModel = model('common/member/Member');
        $field = 'id, sex, status, invite_code,nickname,avatar';
        $member = $memberModel->getInfo(['username' => $mobile], $field);

        if (empty($member['id'])) $this->api_ajaxReturn(SUCCESS, '用户不存在');
        if ($member['status'] == 0) $this->api_ajaxReturn(ERROR, '您已被平台封禁，请联系客服');

        $timestamp = time();

        //更新 member lat lng
        $update_data = [
            'longitude' => $lng,
            'latitude' => $lat,
            'long_lat_geometry' => Db::raw('geomfromtext(CONCAT(\'POINT(\',' . $lng . ',\' \',' . $lat . ',\')\'))'),
            'last_login_time' => $timestamp
        ];
        $res = $memberModel->editByID($member['id'], $update_data);

        //获取token
        $token = model('common/member/TokenLogic', 'logic')->getToken($this->platform, $mobile, $timestamp);


        //用户升级操作
        $memberApplyModel = model('common/member/MemberApply');
        $member_apply_list = $memberApplyModel->getList(['member_id' => $member['id']], 1, 'state', 'handle_time desc');
        if ($member_apply_list) {
            $member_apply = $member_apply_list[0];
            $apply = $member_apply['state']; //0待审核 1通过 2，拒绝
        } else {
            $apply = -1;
        }


        $invite_code = $member['invite_code'] ? $member['invite_code'] : '';
        $platform = sysConfig('platform');
        $customer_service_member = $memberModel->getInfoByID($platform['customer_service_member_id'] ?? 1, 'id,nickname,avatar');

        $data = ['customer_service_member' => $customer_service_member, 'mid' => $member['id'], 'apply' => $apply, 't' => $token, 'sex' => $member['sex'], 'nickname' => $member['nickname'], 'avatar' => $member['avatar'], 'invite_code' => $invite_code];
        $this->api_ajaxReturn(SUCCESS, '登陆成功', $data);
    }

    /**
     * User: Simony
     * Function: 登出
     */
    public function logout()
    {
        $memberId = input('post.id/d', 0);
        $mobile = input('post.mobile', '');
        if (empty($mobile) && $memberId < 1) $this->api_ajaxReturn(ERROR, '缺少必要参数');

        if (!empty($mobile) && !preg_match(SmsService::CHECK_PHONE, $mobile)) $this->api_ajaxReturn(ERROR, '手机号码不正确');

        $token = $this->token;
        $tokenModel = model('common/member/Token');
        $memberModel = model('common/member/Member');
        if (empty($token)) {
            if ($memberId == 0 && $mobile) {
                $memberId = $memberModel->getVal('id', ['username' => $mobile]);
            }

            if ($dbToken = $tokenModel->getInfo(['member_id' => $memberId, 'platform' => $this->platform])) {
                Cache::rm($this->platform . '-' . $dbToken['token']);
                $tokenModel->rm(['id' => $dbToken['id']]);
            }
        } else {
            if ($dbToken = $tokenModel->getInfo(['token' => $token])) {
                $tokenModel->rm(['id' => $dbToken['id']]);
            }
            Cache::rm($this->platform . '-' . $token);
        }
        $this->api_ajaxReturn(SUCCESS, '退出登陆成功');
    }

    public function getSmsCode()
    {
        $mobile = input('post.mobile', '');
        if (empty($mobile)) $this->api_ajaxReturn(ERROR, '手机号码不能为空');
        $check = SmsService::CHECK_PHONE;
        if (!preg_match($check, $mobile)) $this->api_ajaxReturn(ERROR, '手机号码不正确');

        $res = SmsService::send($mobile, SmsService::SMS_LOGIN);
        $res['status'] ? $this->api_ajaxReturn(SUCCESS, $res['msg']) : $this->api_ajaxReturn(ERROR, $res['msg']);
    }

    /**
     * User: Simony
     * Function:注册
     */
    public function register()
    {
        //params
        $mobile = input('post.mobile', '');
        $code = input('post.code', '');
        $sex = input('post.sex/d', 1);
        $nickname = input('post.nickname', '');
        $province = input('post.province/d', '');
        $city = input('post.city/d');
        $district = input('post.district/d');
        $birthday = input('post.birthday/s');
        $content_types = input('post.content_types');
        $expect_object = input('post.expect_object', '');
        $wechat = input('post.wechat', '');
        $wechat_hide = input('post.wechat_hide', '');
        $longitude = input('post.longitude', 113.278121);
        $latitude = input('post.latitude', 23.135911);
        $height = input('post.height/d', 0);
        $weight = input('post.weight/d', 0);
        $type = input('post.type/d', 2);
        $openid = input('post.identification/s', '');

        if ($openid != '') {
            $wechatUserModel = model('common/wechat/WechatUser');
            $wechatUser = $wechatUserModel->getUserInfo($openid);
            if (empty($wechatUser)) $this->api_ajaxReturn(ERROR, '微信用户不存在，请先授权注册');
            if ($wechatUser['member_id'] != 0) $this->api_ajaxReturn(ERROR, '微信号被占用');
        }


        $add_data = [
            'username' => $mobile,
            'sex' => $sex,
            'nickname' => $nickname,
            'province' => $province,
            'city' => $city,
            'district' => $district,
            'birthday' => $birthday,
            'content_types' => $content_types,
            'expect_object' => $expect_object,
            'wechat' => $wechat,
            'wechat_hide' => $wechat_hide,
            'longitude' => $longitude,
            'latitude' => $latitude,
            'long_lat_geometry' => Db::raw('geomfromtext(CONCAT(\'POINT(\',' . $longitude . ',\' \',' . $latitude . ',\')\'))'),
            'last_login_time' => time(),
            'recommend_dept' => 0,
            'create_time' => time(),
        ];

        //model
        $valdate = validate('mobileapp/member');
        $memberModel = model('common/member/Member');
        $fileLogic = model('common/file/FileLogic', 'logic');

        if (empty($code)) $this->api_ajaxReturn(ERROR, '验证码不能为空');
        if (!in_array($type, [1, 2])) $this->api_ajaxReturn(ERROR, '头像上传类型有误');
        if (!$valdate->check($add_data, [], 'register')) $this->api_ajaxReturn(ERROR, $valdate->getError());
        $verify = SmsService::verify($mobile, $code);
        if (!$verify['status']) $this->api_ajaxReturn(ERROR, $verify['msg']);


        $member = $memberModel->getInfo(['username' => $mobile], 'id');
        if (!empty($member)) $this->api_ajaxReturn(ERROR, '该用户已存在');


        //上传文件
        $upload_res = $type == 1 ? $fileLogic->uploadImg(config('app.image_path.avatar'), false) : $fileLogic->base64Image(config('app.image_path.avatar'), false);
        if ($upload_res['code'] != SUCCESS) $this->api_ajaxReturn($upload_res['code'], $upload_res['msg']);

        $add_data['avatar'] = $upload_res['result']['absoluteUrl'];
        if (!empty($height)) $add_data['height'] = $height;
        if (!empty($weight)) $add_data['weight'] = $weight;

        Db::startTrans();

        $mid = $memberModel->add($add_data);
        if (!$mid) {
            Db::rollback();
            $this->api_ajaxReturn(ERROR, '系统维护中，请稍后注册');
        }
        if ($openid != '') {
            $res = $wechatUserModel->edit(['openid' => $openid], ['member_id' => $mid]);
            if (!$res) {
                Db::rollback();
                $this->api_ajaxReturn(ERROR, '更新失败');
            }
        }

        $set_res = $memberModel->setValByID($mid, ['recommend_str' => $mid]);
        if (!$set_res) {
            Db::rollback();
            $this->api_ajaxReturn(ERROR, '更新路径失败');
        }

        Db::commit();
        $token = model('common/member/TokenLogic', 'logic')->getToken($this->platform, $mobile, time());
        Cache::rm($mobile);

        (new \easemob\EasemobIm())->createUser($mid, $add_data['nickname'], md5($mid . 'aawwff'));
        model('common/EasemoblmLogic', 'logic')->joinSysGroup($mid);

        $platform = sysConfig('platform');
        $customer_service_member = $memberModel->getInfoByID($platform['customer_service_member_id'] ?? 1, 'id,nickname,avatar');


        $superior_exists = 0;
        $memberInviteTempModel = model("common/member/MemberInviteTemp");
        $member_invite_temp = $memberInviteTempModel->getInfo(['username' => $mobile]);
        if ($member_invite_temp) {
            Db::startTrans();
            $res = model('common/member/MemberLogic', 'logic')->setInviteCode($mid, $member_invite_temp['parent_invite_code']);
            if ($res['code'] == SUCCESS) {
                $superior_exists = 1;
                Db::commit();
            } else {
                Db::rollback();
            }
            $memberInviteTempModel->del(['username' => $mobile]);
        }


        $this->api_ajaxReturn(SUCCESS, '注册成功', ['superior_exists'=>$superior_exists,'customer_service_member' => $customer_service_member, 'mid' => $mid, 't' => $token, 'sex' => $sex, 'nickname' => $add_data['nickname'], 'avatar' => $add_data['avatar']]);

    }

    /**
     * 微信登陆
     */
    public function wechatLogin()
    {
        $code = input('post.code', '');
        $lng = input('post.longitude', 113.278121);
        $lat = input('post.latitude', 23.135911);
        if (empty($code)) $this->api_ajaxReturn(ERROR, '授权代码不能为空');
        // 获取token
        $res = WechatService::getToken($code);
        if (!$res['status']) $this->api_ajaxReturn(ERROR, $res['msg']);

        $data = $res['data'];
        $res = WechatService::getUserInfo($data);
        if (!$res['status']) $this->api_ajaxReturn(ERROR, $res['msg']);
        $data = $res['data'];
        if (empty($data['openid']) || empty($data['unionid'])) $this->api_ajaxReturn(ERROR, '获取用户信息失败');
        $wechatModel = model('common/wechat/WechatUser');
        $res = $wechatModel->getUserInfo($data['openid']);
        $time = time();
        $dbData = [
            'nickname' => isset($data['nickname']) ? $wechatModel->emojiEncode($data['nickname']) : '',
            'sex' => isset($data['sex']) ? $data['sex'] : 0,
            'province' => isset($data['province']) ? $data['province'] : '',
            'city' => isset($data['city']) ? $data['city'] : '',
            'country' => isset($data['country']) ? $data['country'] : '',
            'headimgurl' => isset($data['headimgurl']) ? $data['headimgurl'] : '',
            'access_token' => $data['access_token'],
            'refresh_token' => $data['refresh_token'],
            'update_time' => $time
        ];
        if (empty($res['id'])) {
            $res['id'] = $wechatModel->add(array_merge($dbData, [
                'member_id' => 0, 'create_time' => $time,
                'openid' => $data['openid'], 'unionid' => $data['unionid']
            ]));
            $res['member_id'] = $res['member_sex'] = 0;
            $res['invite_code'] = $res['username'] = '';
            $res['status'] = 1;
        } else {
            $wechatModel->edit(['id' => $res['id']], $dbData);
        }
        if ($res['member_id'] == 0) $this->api_ajaxReturn(SUCCESS, '用户不存在', ['t' => '', 'sex' => $dbData['sex'] == 0 ? 1 : $dbData['sex'], 'nickname' => $dbData['nickname'], 'wechat_auth' => $data['openid']]);
        if ($res['status'] == 0) $this->api_ajaxReturn(ERROR, '您已被平台封禁，请联系客服');
        //更新 member lat lng
        $update_data = [
            'longitude' => $lng,
            'latitude' => $lat,
            'long_lat_geometry' => Db::raw('geomfromtext(CONCAT(\'POINT(\',' . $lng . ',\' \',' . $lat . ',\')\'))'),
            'last_login_time' => $time
        ];
        $memberModel = model('common/member/Member');
        $memberModel->edit(['username' => $res['username']], $update_data);
        //获取token
        $token = model('common/member/TokenLogic', 'logic')->getToken($this->platform, $res['username'], $time);
        $invite_code = $res['invite_code'] ? $res['invite_code'] : '';

        $customer_service_member = $memberModel->getInfoByID($platform['customer_service_member_id'] ?? 1, 'id,nickname,avatar');
        $this->api_ajaxReturn(SUCCESS, '登陆成功', ['customer_service_member' => $customer_service_member, 'mid' => $res['member_id'], 't' => $token, 'sex' => $res['member_sex'], 'avatar' => $res['avatar'] ?? '', 'nickname' => $res['nickname'] ?? '', 'mobile' => $res['username'], 'invite_code' => $invite_code]);
    }

    /**
     * User: Simony
     * Function:合并用户（无则注册） 待定
     */
    public function mergeWechatMember()
    {
        //params
        $openid = input('post.identification', '');
        $mobile = input('post.mobile', '');
        $code = input('post.code', '');

        $lng = input('post.longitude', 113.278121);
        $lat = input('post.latitude', 23.135911);

        if (empty($mobile)) $this->api_ajaxReturn(ERROR, '手机号码不能为空');
        if (empty($code)) $this->api_ajaxReturn(ERROR, '验证码不能为空');
        $verify = SmsService::verify($mobile, $code);
        if (!$verify['status']) $this->api_ajaxReturn(ERROR, $verify['msg']);

        $wechatUserModel = model('common/wechat/WechatUser');
        $wechatUser = $wechatUserModel->getUserInfo($openid);
        if (empty($wechatUser)) $this->api_ajaxReturn(ERROR, '微信用户不存在，请先授权注册');


        $member = $wechatUserModel->getInfoByMobile($mobile);
        if (empty($member)) $this->api_ajaxReturn(JUMP_LOGIN, '去注册', $wechatUser);
        if ($member['openid'] != '') $this->api_ajaxReturn(ERROR, '请先解绑原用户');


        if ($wechatUser['member_id'] != 0) { //绑定过
            $member['id'] == $wechatUser['member_id'] ? $this->api_ajaxReturn(ERROR, '请勿重复绑定') : $this->api_ajaxReturn(ERROR, '该手机号已绑定其他账户');
        }


        //下面合并用户
        Db::startTrans();
        $res = $wechatUserModel->editByID($wechatUser['id'], ['member_id' => $member['id']]);

        if (!$res) {
            Db::rollback();
            $this->api_ajaxReturn(ERROR, '更新失败');
        }

        $timestamp = time();
        //更新 member lat lng
        $update_data = [
            'longitude' => $lng,
            'latitude' => $lat,
            'long_lat_geometry' => Db::raw('geomfromtext(CONCAT(\'POINT(\',' . $lng . ',\' \',' . $lat . ',\')\'))'),
            'last_login_time' => $timestamp,
        ];

        $res = model('common/member/Member')->editByID($member['id'], $update_data);
        if (!$res) {
            Db::rollback();
            $this->api_ajaxReturn(ERROR, '更新失败');
        }

        //获取token
        $token = model('common/member/TokenLogic', 'logic')->getToken($this->platform, $mobile, $timestamp);
        Db::commit();
        //用户升级操作
        $invite_code = $member['invite_code'] ? $member['invite_code'] : '';
        $data = ['mid' => $member['id'], 't' => $token, 'sex' => $member['sex'], 'invite_code' => $invite_code];
        $this->api_ajaxReturn(SUCCESS, '绑定成功', $data);

    }
}
